import os, _pg
import svn, patchchecker
import project

def setupTables(db):
    q = """
CREATE TABLE Patches(
	PatchID		serial		NOT NULL,
	TargetFileID	int		UNIQUE references Files(FileID),
	TargetFileName	varchar(256)	NOT NULL,
	TargetDir	varchar(256)	NOT NULL,
	SourceDir	varchar(256)	NOT NULL,
	SourceFileName	varchar(256)	NOT NULL,
	body		text  		NOT NULL,
	patchOutput	text		,
	MessageID	varchar(200)	references Messages(MessageID) NOT NULL,
	suc		int		,
	fail		int		,
	fuzzSuc	int		,
	offsetSuc	int		,
PRIMARY KEY  (PatchID)
);
"""
    dropq = """
drop table patches cascade;
"""
    try:
        print "cleaning patches tables..."
        db.query(dropq)
        print "...OK!"
    except _pg.ProgrammingError:
            print "could not drop tables"
    try:
        print "creating patches tables..."
        db.query(q)
        print "...OK!"
    except _pg.ProgrammingError, e:
        print "could not create tables"
        raise project.ProjectError("Could not create tables, cause:" + str(e))

   
def start(proj, log):
    db = proj.getDatabase()
    repo = proj.getSVNRepository()
    setupTables(db)
    if proj.has_key('patchWindow'):
        if len(proj['patchWindow']) == 2:
            (backwardWindow, forwardWindow) = proj['patchWindow']
        else:
            raise project.ProjectError("patchWindow value in project file needs 2 numbers")
    else:
        raise project.ProjectParameterError("patchWindow")
    log.write("setup clean patches table, about to begin parsing messages for patches. Window: -%s to %s days" % (backwardWindow, forwardWindow))
    patchchecker.findAcceptedPatches(db, repo, int(backwardWindow), int(forwardWindow), log)    
